package main

import (
	"bufio"
	"fmt"
	"net"
)

func process(conn net.Conn) {
	defer conn.Close()

	for {
		reader := bufio.NewReader(conn)
		var buff [512]byte
		n, err := reader.Read(buff[:])
		if err != nil {
			fmt.Println("read from client failed, err:", err)
			break
		}
		recvStr := string(buff[:n])
		fmt.Println("收到客户端的消息：", recvStr)
		conn.Write([]byte(fmt.Sprintln("收到客户端的消息：", recvStr)))
	}

}

func main() {
	//1.创建监听socket
	fmt.Println("")
	listen, error := net.Listen("tcp", ":8888")
	if error != nil {
		fmt.Println("listen failed, err:", error)
		return
	}
	//2.等待客户端连接
	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("accept failed, err:", err)
			continue
		}
		//3. 处理客户端连接
		go process(conn)
	}
}
